package com.wenhai.xiaomage.spring.ioc.overview.dependency.lookup;

import com.wenhai.xiaomage.spring.ioc.overview.dependency.annotation.Super;
import com.wenhai.xiaomage.spring.ioc.overview.dependency.domain.User;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.ListableBeanFactory;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.Map;

/**
 * @Author:wenhai
 * @Description: 依赖查找
 * @Date:2020/3/4
 */
public class DependencyLookupNameDemo {
    public static void main(String[] args) {
        BeanFactory beanFactory = new ClassPathXmlApplicationContext("classpath:/META-INF/dependency-lookup-context.xml");
        // 实时查找
        lookupInRealTime(beanFactory);
        // 延迟查找
        lookupInLazy(beanFactory);
        // 类型查找
        lookupByType(beanFactory);
        // 按照类型查找集合对象
        lookupCollectionByType(beanFactory);
        // 按照注解查找集合对象
        lookupByAnnotation(beanFactory);

    }

    @SuppressWarnings("unchecked")
    private static void lookupByAnnotation(BeanFactory beanFactory) {
        System.out.println("注解查找");
        if (beanFactory instanceof ListableBeanFactory) {
            ListableBeanFactory listableBeanFactory = (ListableBeanFactory) beanFactory;
            Map<String, String> users = (Map) listableBeanFactory.getBeansWithAnnotation(Super.class);
            System.out.println(users);
        }
    }

    private static void lookupCollectionByType(BeanFactory beanFactory) {
        System.out.println("类型查找集合对象");
        if (beanFactory instanceof ListableBeanFactory) {
            ListableBeanFactory listableBeanFactory = (ListableBeanFactory) beanFactory;
            Map<String, User> userMap = listableBeanFactory.getBeansOfType(User.class);
            System.out.println(userMap);
        }
    }

    private static void lookupByType(BeanFactory beanFactory) {
        System.out.println("类型查找单个对象");
        User user = beanFactory.getBean(User.class);
        System.out.println(user);

    }

    @SuppressWarnings("unchecked")
    private static void lookupInLazy(BeanFactory beanFactory) {
        System.out.println("延迟查找");
        // 延迟查找
        ObjectFactory<User> user = (ObjectFactory<User>) beanFactory.getBean("objectFactory");
        System.out.println(user.getObject());
    }

    private static void lookupInRealTime(BeanFactory beanFactory) {
        System.out.println("实时查找");
        // 实时查找
        User user = (User) beanFactory.getBean("user");
        System.out.println(user);
    }
}
